<template>
  <div class="select_region_content">
    <div class="region_content" @click="showPopup = true">
      <span class="region_label">{{ selectRegion }}</span>
      <van-icon name="arrow" color="#aeaeae" size="16"></van-icon>
    </div>
    <van-popup v-model:show="showPopup" round position="bottom">
      <van-cascader
        v-model="cascaderValue"
        title="请选择地区"
        :options="options"
        @close="showPopup = false"
        @finish="onFinish"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, defineEmits, defineProps, onMounted, computed } from "vue";
import {
  selectLocationPage, selectSubLocations,
} from "@/network/api";

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["update:modelValue","goodsPageCall"]);

const showPopup = ref(false);
const selectRegion = ref("");
const cascaderValue = ref("");

const options = ref([]);
let optionMap = {};

onMounted(async () => {
  cascaderValue.value = props.modelValue;
  selectRegion.value = optionMap[cascaderValue.value]?.text || "--";

  selectLocationPage({
    current: 1,
    size: 1000,
  }).then((res) => {
    if (res?.data?.data?.records?.length > 0) {
      getOptions(res.data.data.records);
    } else {
      resolve([]);
      //node.isLeaf = true;
    }
  });
});

const getOptions = (result) => {

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(result);
      options.value = result.map(item => ({
        text: item.locationName,
        value:item.id.toString(),
        parentId:item.parentId.toString(),
      }));
      options.value.unshift({
        text: '全部',
        value:null,
        parentId:null,
      });
    }, 300);
  });
};
const onFinish = ({ selectedOptions }) => {
  selectRegion.value = selectedOptions[selectedOptions.length-1].text || "--";
  emit("update:modelValue", cascaderValue.value);
  selectSubLocations({
    parentId: selectedOptions[0].value,
  }).then((res) => {
    if (res?.data?.data?.length > 0) {
      selectedOptions[0].children = res.data.data.map(item => ({
        text: item.locationName,
        value:item.id.toString(),
        parentId:item.parentId.toString(),
      }));
    }
    // 刷新主页
    emit("goodsPageCall", cascaderValue.value);
  });
};
</script>
<style lang="scss" scoped>
.select_region_content {
  .region_content {
    display: flex;
    justify-content: space-around;
    align-items: center;
    .region_label {
      font-size: 14px;
      color: #aeaeae;
      padding-right: 8px;
    }
  }
}
</style>
